package com.sx.micowell.framework.model

import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import com.blankj.utilcode.util.CacheDiskUtils
import com.example.mvvm.base.data.SingleLiveEvent
import com.example.mvvm.base.vm.BaseViewModel
import com.example.mvvm.rx.RxBus
import com.example.mvvm.until.LogUtils
import com.example.mvvm.until.SPUtils
import com.example.mvvm.until.ToastUtils
import com.miloyu.modelnet.cache.CacheBean
import com.miloyu.modelnet.cache.CacheManager
import com.miloyu.modelnet.network.ApiResponse
import com.miloyu.modelnet.network.HttpClient
import com.miloyu.modelnet.network.tools.RxUtils
import com.miloyu.modelnet.response.UserInfoVO
import com.miloyu.modelnet.response.log
import com.sx.micowell.framework.app.AppConstant
import com.sx.micowell.framework.app.IntentKey
import com.sx.micowell.framework.app.SPKey
import com.sx.micowell.framework.arouth.RouteManager
import com.sx.micowell.framework.binding.BindingCommand
import com.sx.micowell.framework.binding.impl.IBindingAction
import com.sx.micowell.framework.entity.AccountBean
import com.sx.micowell.framework.tools.EventInfo
import com.tuya.smart.home.sdk.TuyaHomeSdk
import io.reactivex.android.schedulers.AndroidSchedulers

/**
 * @Description
 * @Author 梁浩文
 * @Date 2021/7/27 15:19
 */
class MineModel : BaseViewModel() {

    override fun registerRxBus() {
        super.registerRxBus()
        addSubscribe(
            RxBus.getDefault().toObservable(EventInfo::class.java)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { event ->
                    if (event.type == AppConstant.EVENT_LOGIN_OUT) {
//                        RouteManager.getInstance().intentLogin()
//                        // 退出登录
//                        context.finishEvent.call()
                        loginSwitchEvent.value = null
                    } else if (event.type == AppConstant.EVENT_LOGIN_SWITCH) {
                        loginSwitchEvent.value = event.data as AccountBean?
                    }
                }
        )
    }

    var loginSwitchEvent: SingleLiveEvent<AccountBean> = SingleLiveEvent()

    val userInfoEvent : SingleLiveEvent<UserInfoVO> = SingleLiveEvent()

    // 刷新
    val onRefreshCommand: BindingCommand<Void> = BindingCommand(IBindingAction {
        LogUtils.d("onRefreshCommand:")
        userInfo()
    })

    // 头像点击事件
    val headImageOnClickCommand = BindingCommand<Any>(IBindingAction {
        context.startContainerActivity(
            (RouteManager.getInstance().getSettingFragment().javaClass.canonicalName)
        )
    })

    // 消息点击事件
    val messageOnClickCommand = BindingCommand<Any>(IBindingAction {
        RouteManager.getInstance().intentMineNews()
    })

    // 开通会员
    val openMemberOnClickCommand = BindingCommand<Any>(IBindingAction {
        val bundle = Bundle()
        bundle.putSerializable(IntentKey.DATA, userInfoEvent.value)
        context.startContainerActivity(
            userInfoEvent.value?.let { RouteManager.getInstance().getMemberFragment(it).javaClass.canonicalName },
            bundle
        )
    })

    // 邀请好友
    val inviteFriendOnClickCommand = BindingCommand<Any>(IBindingAction {
        context.startContainerActivity(
            RouteManager.getInstance().getInviteFriendFragment().javaClass.canonicalName
        )
    })

    // 学过的课
    val learnedCourseOnClickCommand = BindingCommand<Any>(IBindingAction {
        context.startContainerActivity(
            RouteManager.getInstance().getLearnedCourseFragment().javaClass.canonicalName
        )
    })

    // 我的收藏
    val mineCollectOnClickCommand = BindingCommand<Any>(IBindingAction {
        context.startContainerActivity(
            RouteManager.getInstance().getMineCollectFragment().javaClass.canonicalName
        )
    })

    // 智能设备
    val intelligentDeviceOnClickCommand = BindingCommand<Any>(IBindingAction {
        if (TuyaHomeSdk.getUserInstance().isLogin) {
            context.startContainerActivity(
                RouteManager.getInstance().getDeviceBindListFragment().javaClass.canonicalName
            )
        } else {
            RouteManager.getInstance().intentDeviceLogin()
        }
    })

    // 我的设置
    val settingOnClickCommand = BindingCommand<Any>(IBindingAction {
        context.startContainerActivity(
            (RouteManager.getInstance().getSettingFragment().javaClass.canonicalName)
        )
    })

    // 帮助中心
    val helpCenterListOnClickCommand = BindingCommand<Any>(IBindingAction {
        context.startContainerActivity(
            (RouteManager.getInstance().getHelpCenterFragment().javaClass.canonicalName)
        )
    })

    fun userInfo() {

        addSubscribe(HttpClient.instance.apiService
            .userInfo()
            .doOnSubscribe {
                it.CacheBean<UserInfoVO>("userInfo",UserInfoVO::class.java)?.let {
                    userInfoEvent.postValue(it)
                }
            }
            .compose(RxUtils.compose())
            .subscribeWith(object : ApiResponse<UserInfoVO>() {

                override fun success(data: UserInfoVO?, msg: String?) {
                    data?.let {
                        userInfoEvent.value = it
                        // 本地数据缓存
                        CacheDiskUtils.getInstance().put(
                            AppConstant.CacheKey.CACHE_USER_INFO, it,
                            AppConstant.CacheKey.CACHE_SAVE_TIME_SECONDS)
                        ui.refreshEvent.value = true
                        SPUtils.getInstance().put(SPKey.SP_VIP, it.isVip)
                    }

                }

                override fun onFail(e: Throwable?, errorMsg: String?) {
                    //ToastUtils.showShort("$errorMsg")
                    ui.refreshEvent.value = false
                }

            })
        )

    }


}